<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

class Pay extends Api
{
    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = ['*'];
    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = ['*'];

    /**************************************** 微信支付 开始 ***************************************/

    //微信支付DEMO
    public function wx_pay()
    {
        //TODO 订单逻辑处理

        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        $domain    = $_SERVER['HTTP_HOST'];
        $notifyUrl = $http_type . $domain . '/api/pay/wx_pay_result';
        $PayLogic  = new \app\api\Logic\PayLogic();
        $order_sn  = "";//订单编号
        $amount    = '';//支付金额
        $openid    = '';//openid
        $res       = $PayLogic->createPay($notifyUrl, $order_sn, $amount, 'WXPAY', $openid);
        if ($res['code'] != 1) {
            $this->error($res['msg']);
        } else {
//            model('PayLogModel')->where('id', $pay_log['id'])->update(['pay_json' => json_encode($res['data'], 256)]);

            $return_data                      = [];
            $return_data['result']['payData'] = stripslashes($res['data']['data']['pay_info']);
            $return_data['result']['payData'] = json_decode($return_data['result']['payData'], true);

            $this->success('成功', $return_data);
        }
    }

    //微信支付回调
    public function wx_pay_result()
    {
        $resPost = $this->request->request();
        inventedPayLog('微信支付回调值：', json_encode($resPost, 256));

        //判断是否正常
        if (@$resPost['resp_code'] != '00000000') { //受理失败
            return api_return();
        }
        $respDataJsonStr = html_entity_decode(@$resPost["resp_data"]);
        //解析下返回值
        $result = json_decode($respDataJsonStr, true);
        if (!isset($result['req_seq_id'])) { //没有订单号
            return api_return();
        }

        $rt2_orderId     = @$result['req_seq_id'];       //订单号
        $rt5_orderAmount = @floatval($result['pay_amt']);//实付金额
        $hf_seq_id       = @$result['hf_seq_id'];        //原交易全局流水号

        Db::startTrans();
        try {
            $order = db('pay_log')->where('order_sn', $rt2_orderId)->lock(true)->find();
            if (empty($order) || $order['status'] != 0) {
                Db::rollback();

                return api_return();
            }

            if ($order['status'] == 1) {
                Db::rollback();

                //返回给调用者
                $resultDg = ["code" => "90000", "message" => "成功", "data" => "回调执行成功",];
                echo json_encode($resultDg);
                exit;
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            inventedPayLog('微信支付回调事务异常：', $e->getMessage());
            api_return();
        }

        //返回给调用者
        $resultDg = ["code" => "90000", "message" => "成功", "data" => "回调执行成功",];
        echo json_encode($resultDg);
        exit;
    }

    /**************************************** 微信支付 结束 ***************************************/

    /**************************************** 微信退款 开始 ***************************************/

    //微信退款DEMO
    public function refund_demo()
    {
        $refund         = '0.00';    //退款金额
        $org_req_date   = "20250821";//原交易请求日期
        $transaction_id = '';        //原交易订单编号

        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        $domain    = $_SERVER['HTTP_HOST'];
        $notifyUrl = $http_type . $domain . '/api/pay/wx_refund_result';

        $refund_data                 = [];
        $refund_data['notifyUrl']    = $notifyUrl;      //回调地址
        $refund_data['amount']       = $refund;         //退款金额
        $refund_data['org_req_date'] = $org_req_date;   //原交易请求日期
        $refund_data['org_order_sn'] = $transaction_id; //原交易订单编号
        $PayLogic                    = new \app\api\Logic\PayLogic();
        $result                      = $PayLogic->refund($refund_data);
        if ($result['code'] != 1) {
            Db::rollback();
            throw new \Exception($result['msg']);
        }
    }

    //微信退款回调
    public function wx_refund_result()
    {
        $resPost = $this->request->request();
        inventedPayLog('微信退款[松果铺]2回调值：', json_encode($resPost, 256));

        //判断是否正常
        if (@$resPost['resp_code'] != '00000000') { //受理失败
            return api_return();
        }
        $respDataJsonStr = html_entity_decode(@$resPost["resp_data"]);
        //解析下返回值
        $result = json_decode($respDataJsonStr, true);
        if (!isset($result['req_seq_id'])) { //没有订单号
            return api_return();
        }

        $req_seq_id = @$result['req_seq_id'];       //订单号
        $ord_amt    = @floatval($result['ord_amt']);//退款金额
        $hf_seq_id  = @$result['hf_seq_id'];        //全局流水号

        Db::startTrans();
        try {

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            inventedPayLog('微信退款回调事务异常：', $e->getMessage());
            api_return();
        }

        //返回给调用者
        $resultDg = ["code" => "90000", "message" => "成功", "data" => "回调执行成功",];
        echo json_encode($resultDg);
        exit;
    }

    /**************************************** 微信退款 结束 ***************************************/
}